package aom.ju.ss.view.pay

import android.content.Intent
import android.os.Message
import androidx.recyclerview.widget.LinearLayoutManager
import aom.ju.ss.R
import aom.ju.ss.databinding.CutPlaceOrderBinding
import aom.ju.ss.databinding.CutPlaceOrderItemBinding
import aom.ju.ss.databinding.CutPlaceOrderItemItemBinding
import aom.ju.ss.mode.*
import aom.ju.ss.mode.LpKey.CloseOrderRelatedPage
import aom.ju.ss.utils.*
import aom.ju.ss.utils.http.LP_API
import aom.ju.ss.utils.http.LP_API.address_list
import aom.ju.ss.utils.http.LP_API.create_order
import aom.ju.ss.utils.http.LP_API.get_freight
import aom.ju.ss.utils.http.LP_API.get_pay_info
import aom.ju.ss.utils.http.OKHttpUtils
import aom.ju.ss.utils.pay.WxXcxzf
import aom.ju.ss.view.base.BaseActivity
import aom.ju.ss.view.base.PAdapter
import aom.ju.ss.view.user.AddressListActivity
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import org.json.JSONArray
import org.json.JSONObject
import java.lang.reflect.Type


/**
 * 砍价 品牌 提交订单
 */
class CutPlaceAnOrder : BaseActivity() {
    lateinit var binding: CutPlaceOrderBinding

    var list = arrayListOf<GoodsInfoData>()
    var allPrice: Double = 0.0

    var goodsType = ""
    var orderType = ""

    var goodsNum = 0
    override fun init() {
        binding = viewBinding as CutPlaceOrderBinding
        val type: Type = object : TypeToken<List<GoodsInfoData>>() {}.type
        list = Gson().fromJson(intent.getStringExtra("data"), type)
        goodsType = intent.getStringExtra("goodsType")!!
        orderType = intent.getStringExtra("orderType")!!
        getAdd()

        for (a in list) {
            a.skus?.let {
                for (c in it) {
                    goodsNum++
                    if (c.price.toDoubleOrNull() != null) {
                        allPrice += BigDecimalUtils.mul(c.price, c.num, 2).toDouble()
                    }
                }
            }
        }
        binding.num.text = allPrice.toString()

        binding.allGoodsNum.text = "共" + goodsNum + "件，合计:"
        binding.tvCountMoney.text = allPrice.toString()

        binding.rec.layoutManager = LinearLayoutManager(activity)
        binding.rec.adapter = PAdapter(
            list, R.layout.cut_place_order_item
        ) { bb, position ->
            val ib = bb as CutPlaceOrderItemBinding
            ib.name.text = list[position].shop_info.name
            ib.rec.layoutManager = LinearLayoutManager(activity)
            ib.check.VG(false)
            list[position].skus?.let { skus ->
                ib.rec.adapter = PAdapter(
                    skus, R.layout.cut_place_order_item_item
                ) { b, ip ->
                    val bbb = b as CutPlaceOrderItemItemBinding
                    bbb.check.VG(false)
                    bbb.line.view.VG(position != skus.size - 1)
                    bbb.sku = skus[ip]
                    bbb.info = list[position]
                }
            }
        }

        val num = if (orderType == "1") list[0].skus!![0].num else ""
        val sku_id = if (orderType == "1") list[0].skus!![0].id.toString() else ""
        val goods_id = if (orderType == "1") list[0].id.toString() else ""

        val cart_ids = if (orderType == "2") intent.getStringExtra("cart_ids")!! else ""

        binding.btnBuy.setOnClickListener {
            if (addid == "") {
                "请选择收货地址".show
                return@setOnClickListener
            }

            OKHttpUtils(activity)
                .SetApiUrl(LP_API.create_order)
                .SetKey(
                    "type",
                    "order_type",
                    "address_id",
                    "goods_id",
                    "sku_id",
                    "num",
                    "remark",
                    "cart_ids",
                    "delivery_way"
                )
                .SetValue(
                    "1",
                    goodsType,
                    addid,
                    goods_id,
                    sku_id,
                    num,
                    binding.mark.text.toString(),
                    cart_ids,
                    "1"
                )
                .POST(this)
        }

    }

    //订单类型  1普通订单  2砍价订单  3抢券订单  4易货订单  5易货促销订单 ，购物车下单默认普通订单，暂不支持其他类型
    private fun getfreight() {
        val js = JSONArray()
        for (i in list) {
            val jb = JSONObject()
            i.skus?.let {
                for (a in it) {
                    jb.put("goods_id", i.id.toString())
                    jb.put("sku_id", a.id.toString())
                    jb.put("num", a.num)
                    js.put(jb)
                }
            }
        }

        OKHttpUtils(activity, false)
            .SetApiUrl(get_freight)
            .SetKey("goods", "order_type", "address_id")
            .SetValue(js.toString(), goodsType, addid)
            .POST(this)

    }

    /**
     * 获取收货地址
     */
    private fun getAdd() {
        OKHttpUtils(activity, false)
            .SetApiUrl(address_list)
            .POST(this)


    }

    var addid = ""
    override fun ok(jsonString: String, httpTY: String) {
        super.ok(jsonString, httpTY)
        when (httpTY) {
            address_list -> {//获取收货地址
                val mode = Gson().fromJson(jsonString, ReceivingAddressList::class.java)
                mode.data.let {
                    if (it != null && it.isNotEmpty()) {
                        for (a in it) {
                            if (a.is_default == "1") {
                                binding.addr.info = a
                                addid = a.id
                                getfreight()
                            }
                        }
                    }
                }
                binding.addr.layAddress.setOnClickListener {
                    startResult(AddressListActivity::class.java, 199, "0")
                }
            }
            get_freight -> {//获取邮费
                val mode = Gson().fromJson(jsonString, Fare::class.java)
                mode.data?.let {
                    binding.num.text = (allPrice + it.freight).toString()
                    binding.tvCountMoney.text = (allPrice + it.freight).toString()
                    binding.yunfei.text = "运费¥" + it.freight
                }
            }
            create_order -> {
                val mode = Gson().fromJson(jsonString, GetPayInfo::class.java)

                start(
                    PayActivity::class.java, arrayListOf(
                        Gson().toJson(
                            WxXcxzf(
                                business_type = "0",
                                pay_type = "4",
                                pay_id = mode.data.pay_id.toString(),
                                apitype = "0",
                                api = get_pay_info,
                                allPrice = binding.tvCountMoney.text.toString()
                            )
                        ), goodsType
                    )
                )
            }
            get_pay_info -> {//支付


            }
        }
    }

    override fun onRestart() {
        super.onRestart()
        getAdd()
    }

    override fun error(e: String, jsonString: String, httpTY: String) {
        super.error(e, jsonString, httpTY)
        e.show
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK) {
            if (requestCode == 199) {
                val data =
                    Gson().fromJson(data?.getStringExtra("data"), ReceivingAddressData::class.java)
                binding.addr.info = data
                addid = data.id
                getfreight()
            }
        }
    }

    override val lay: Int = R.layout.cut_place_order
    override fun callBack(event: Message) {
        super.callBack(event)
        if (event.arg1 == CloseOrderRelatedPage) {
            finish()
        }
    }
}
